package com.rectcircle.config

import org.squeryl.PrimitiveTypeMode._
import org.squeryl.{ForeignKeyDeclaration, Schema}
import com.rectcircle.model.{Author, Book, Borrowal, Reader}

object LibraryDbSchema extends Schema  {
	
	def tx[A](a: => A): A = {
		inTransaction(a)
	}
	
	//当表名称与类名称不匹配时，在此处指定
	val authors = table[Author]("AUTHORS")
	val books = table[Book]
	//val borrowals = table[Borrowal]
	val readers = table[Reader]
	
	//定义一对多映射关系
	val authorToBooks = oneToManyRelation(authors,books).
	  via((a,b)=>a.id===b.authorId)
	
	//定义一个多对多关系
	val borrowals = manyToManyRelation(readers,books).
	  via[Borrowal]((r,b,bor)=>(r.id===bor.readerId, b.id===bor.bookId))
	
	
	//定义外键类型
	override def applyDefaultForeignKeyPolicy(foreignKeyDeclaration: ForeignKeyDeclaration) =
		foreignKeyDeclaration.constrainReference
	
//	//级联删除
//	//如果删除author，将删除相关的books
//	authorToBooks.foreignKeyDeclaration.constrainReference(onDelete cascade)
//	//如果删除book，将删除reader
//	borrowals.leftForeignKeyDeclaration.constrainReference(onDelete cascade)
	
	on(authors)(s ⇒ declare(
		s.id         is(primaryKey,autoIncremented),
		s.email      is(unique, indexed("idxEmailAddresses")) , //设置索引
		s.firstName  is(indexed),
		s.lastName   is(indexed, dbType("varchar(255)")), // 设置数据库列的类型
		columns(s.firstName, s.lastName) are(indexed)
	))

	on(books)(b⇒ declare(
		b.id is(primaryKey,autoIncremented)
	))
	
	on(borrowals)(b => declare(
		b.numberOfPhonecallsForNonReturn defaultsTo (0)
	))
	
	on(readers)(r=>declare(
		r.id is(primaryKey,autoIncremented),
		r.username is (indexed)
	))

	//删除数据表方法为了安全通常，不允许访问。测试打开它
	override def drop = super.drop
	
}